package com.xuexiang.xuidemo.fragment.expands;/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.tencent.mmkv.MMKV;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.searchview.MaterialSearchView;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.adapter.SimpleOrderRecyclerAdapter;
import com.xuexiang.xuidemo.adapter.SimpleOrderRecyclerAdapterKc;
import com.xuexiang.xuidemo.base.BaseFragment;
import com.xuexiang.xuidemo.domain.Order;
import com.xuexiang.xuidemo.fragment.components.textview.supertextview.SuperCkClickFragment;
import com.xuexiang.xuidemo.fragment.components.textview.supertextview.SuperKCClickFragment;
import com.xuexiang.xuidemo.utils.update.OkHttpUpdateHttpServiceImpl;
import com.xuexiang.xupdate.proxy.IUpdateHttpService;
import com.xuexiang.xutil.common.ObjectUtils;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 库存扫码
 * @author kong
 * @since 2025/03/06
 */
@Page(name = "库存扫码", extra = R.drawable.whole)
public class InventoryFragment extends BaseFragment {
    @BindView(R.id.search_view)
    MaterialSearchView mSearchView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private SimpleOrderRecyclerAdapterKc mAdapter;

    private Handler mLoadingHandler = new Handler(Looper.getMainLooper());

    private Integer page = 1;
    private Integer size = 10;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_inventory_goods;
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.addAction(new TitleBar.ImageAction(R.drawable.icon_action_query) {

            @Override
            @SingleClick
            public void performAction(View view) {
                mSearchView.showSearch();
            }
        });
        return titleBar;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 下拉刷新
        refreshLayout.setOnRefreshListener(refreshLayout12 -> refreshLayout12.getLayout().postDelayed(() -> {
            // 查询订单并赋值
            page = 1;
            orderList(page, size, "");
            refreshLayout12.finishRefresh();
            refreshLayout12.resetNoMoreData();//setNoMoreData(false);
        }, 0));

    }


    @Override
    protected void initViews() {
        mSearchView.setVoiceSearch(false);
        mSearchView.setEllipsize(true);
        mSearchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
        mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                page = 1;
                size = 10;
                orderList(page,size,query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Do some magic
                return false;
            }
        });
        mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
                //Do some magic
            }

            @Override
            public void onSearchViewClosed() {
                //Do some magic
            }
        });
        mSearchView.setSubmitOnClick(true);

        // 初始化列表控件
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        WidgetUtils.initRecyclerView(recyclerView);
        recyclerView.setAdapter(mAdapter = new SimpleOrderRecyclerAdapterKc());

        // 开启自动加载功能（非必须）
        refreshLayout.setEnableAutoLoadMore(true);

        // 下拉刷新
        refreshLayout.setOnRefreshListener(refreshLayout12 -> refreshLayout12.getLayout().postDelayed(() -> {
            // 查询订单并赋值
            page = 1;
            orderList(page, size,"");
            refreshLayout12.finishRefresh();
            refreshLayout12.resetNoMoreData();//setNoMoreData(false);
        }, 0));
        // 上拉加载
        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> refreshLayout1.getLayout().postDelayed(() -> {
            size = size + 10;
            orderList(page, size,"");
        }, 0));

        RefreshHeader header = getRefreshHeader();
        if (header != null) {
            refreshLayout.setRefreshHeader(header);
        }
        // 触发自动刷新
        refreshLayout.autoRefresh();
        // item 点击跳转页面
        mAdapter.setOnItemClickListener((itemView, item, position) ->{
            Gson gson = new Gson();
            String json = gson.toJson(item);
            openPageForResult(SuperKCClickFragment.class,"josnStr",json,200);
        } );

//        mAdapter.setOnItemLongClickListener((itemView, item, position) -> XToastUtils.toast("长按:" + item.getDjbh()));
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (data != null) {
            // 触发自动刷新
            refreshLayout.autoRefresh();
        }
    }

//    @OnClick(R.id.fab)
//    void toSearchActivity(View v) {
//        startActivity(new Intent(getContext(), SearchViewActivity.class));
//    }

    public void orderList(Integer page,Integer size,String query){
        // 获取数据okhttp
        OkHttpUpdateHttpServiceImpl httpService = new OkHttpUpdateHttpServiceImpl();
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("size", size);
        map.put("djbh", query); // 查询的是药品名称
        String base_url = MMKV.defaultMMKV().decodeString("BASE_URL");
        httpService.asyncPost(base_url+"/api/warehouse/kc", map, new IUpdateHttpService.Callback(){
                    @Override
                    public void onSuccess(String s) {
                        System.out.println(s);
                        mLoadingHandler.post(()->{
                            JSONObject json = JSONUtil.parseObj(s);
                            Object objectCur = json.get("content");
                            if (ObjectUtils.isNotEmpty(objectCur)){
                                String recordsStr = String.valueOf(objectCur);
                                Gson gson = new Gson();
                                List<Order> list = gson.fromJson(recordsStr, new TypeToken<List<Order>>(){}.getType());
                                mAdapter.refresh(list);
                            }else {
                                mAdapter.clear();
                            }
                        });
                        XToastUtils.toast("数据加载成功");
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        XToastUtils.toast("数据加载失败");

                    }
                }
        );
    }

    private RefreshHeader getRefreshHeader() {
        try {
            Class<?> headerClass = Class.forName("com.scwang.smartrefresh.header.WaterDropHeader");
            Constructor<?> constructor = headerClass.getConstructor(Context.class);
            return (RefreshHeader) constructor.newInstance(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        if (mSearchView.isSearchOpen()) {
            mSearchView.closeSearch();
        }
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (matches != null && matches.size() > 0) {
                String searchWrd = matches.get(0);
                if (!TextUtils.isEmpty(searchWrd)) {
                    mSearchView.setQuery(searchWrd, false);
                }
            }

            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
